package com.lg.baselibrary.adapter;

import android.content.Context;
import android.support.v4.util.SparseArrayCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.lg.baselibrary.adapter.BaseRecyclerViewHolder.OnItemClickListener;
import com.lg.baselibrary.adapter.BaseRecyclerViewHolder.OnItemLongClickListener;

import java.util.ArrayList;
import java.util.List;
/**
 * Created by LiGang on 2017/5/27.
 * 支持addHeaderView和addFooterView
 * 支持多item布局
 * @param <T>
 */
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    private List<T> mDatas;
    private Context mContext;
    private LayoutInflater mInflater;
    private OnItemClickListener onItemClickListener;
    private OnItemLongClickListener onItemLongClickListener;

    private SparseArrayCompat<View> headerViews = new SparseArrayCompat<>();
    private SparseArrayCompat<View> footerViews = new SparseArrayCompat<>();
    private static final int BASE_ITEM_TYPE_HEADER = 1024;
    private static final int BASE_ITEM_TYPE_FOOTER = 2048;
    public BaseRecyclerViewAdapter(Context context) {
        this.mContext = context;
        this.mDatas = new ArrayList<>();
        mInflater = LayoutInflater.from(context);
    }
    public List<T> getDatas() {
        return mDatas;
    }
    public void setDatas(List<T> mDatas) {
        this.mDatas.clear();
        this.mDatas.addAll(mDatas);
        notifyDataSetChanged();
    }
    public void addDatas(List<T> datas){
        this.mDatas.addAll(datas);
        notifyDataSetChanged();
    }
    public void addDatasFirst(T data){
        this.mDatas.add(0,data);
        notifyDataSetChanged();
    }
    public void addDatasFirst(List<T> datas){
        this.mDatas.addAll(0,datas);
        notifyDataSetChanged();
    }
    public void removeData(int index){
        this.mDatas.remove(index - getHeadersCount());
        notifyDataSetChanged();
    }
    public void removeData(T data){
        this.mDatas.remove(data);
        notifyDataSetChanged();
    }
    public Context getContext() {
        return mContext;
    }
    public LayoutInflater getInflater() {
        return mInflater;
    }

    @Override
    public int getItemViewType(int position) {
        if(isHeader(position)){
            return headerViews.keyAt(position);
        }
        if(isFooter(position)){
            return footerViews.keyAt(position - getHeadersCount() - mDatas.size());
        }
        return getItemViewLayout(position - getHeadersCount());
    }
    /**必须实现该方法，返回position对应的布局文件id**/
    protected abstract int getItemViewLayout(int position);
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(headerViews.get(viewType) != null){
            return new RecyclerView.ViewHolder(headerViews.get(viewType)){
            };
        }
        if(footerViews.get(viewType) != null){
            return new RecyclerView.ViewHolder(footerViews.get(viewType)) {
            };
        }
        BaseRecyclerViewHolder viewHolder = new BaseRecyclerViewHolder(mContext, mInflater.inflate(viewType,parent,false));
        viewHolder.setOnItemClickListener(onItemClickListener);
        viewHolder.setOnItemLongClickListener(onItemLongClickListener);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(isHeader(position) || isFooter(position)){
            return;
        }
        convert((BaseViewHolder) holder,getItem(position),position);
    }
    public T getItem(int position){
        position = position - getHeadersCount();
        return mDatas.get(position);
    }
    public abstract void convert(BaseViewHolder viewHolder, T item, int position);
    @Override
    public int getItemCount() {
        return mDatas.size() + getHeadersCount() + getFootersCount();
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }

    public void addHeaderView(View view) {
        if(headerViews.indexOfValue(view) == -1){
            headerViews.put(BASE_ITEM_TYPE_HEADER + headerViews.size(),view);
        }
    }

    public void addFooterView(View view) {
        if(footerViews.indexOfValue(view) == -1){
            footerViews.put(BASE_ITEM_TYPE_FOOTER + footerViews.size(),view);
        }
    }

    /**
     * 判断是否是头部
     * @param position
     * @return
     */
    private boolean isHeader(int position){
        return position < getHeadersCount();
    }

    /**
     * 判断是否是脚部
     * @param position
     * @return
     */
    private boolean isFooter(int position){
        return position >= mDatas.size() + getHeadersCount();
    }
    public int getHeadersCount(){
        return headerViews.size();
    }
    public int getFootersCount(){
        return footerViews.size();
    }
    /**
     * 重写该方法 当recyclerView的LayoutManager为GridLayoutManager时，
     * 让head和footer占一整行
     * @param recyclerView
     */
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if(layoutManager instanceof GridLayoutManager){
            final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return isHeader(position) || isFooter(position) ? gridLayoutManager.getSpanCount():1;
                }
            });
        }
    }

    /**
     * StaggeredGridLayoutManager中并没有像GridLayoutManager
     * 设置占多少单元格的方法，所以在onViewAttachedToWindow方法中来处理
     * @param holder
     */
    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        int position = holder.getLayoutPosition();
        if(isHeader(position) || isFooter(position)){
            ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
            if(lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams){
                StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) lp;
                params.setFullSpan(true);
            }
        }
    }

}
